// 模拟 API 数据，用于开发和测试
import { BlogPost, UserProfile, Skill, WorkExperience } from '../store';

// 模拟延迟
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

// 模拟博客文章数据
const mockPosts: BlogPost[] = [
  {
    id: 1,
    title: '开始使用React和UMI构建现代Web应用',
    excerpt:
      '本文将介绍如何使用React和UMI框架快速搭建一个现代化的Web应用，包括路由配置、状态管理和UI组件的使用。',
    date: '2023-08-01',
    tags: ['React', 'UMI', '前端开发'],
    views: 1250,
    likes: 42,
  },
  {
    id: 2,
    title: 'Tailwind CSS：实用优先的CSS框架',
    excerpt:
      'Tailwind CSS是一个功能类优先的CSS框架，它提供了低级实用工具类，让你可以直接在HTML中构建自定义设计，而无需编写CSS。',
    date: '2023-07-25',
    tags: ['CSS', 'Tailwind', '设计'],
    views: 980,
    likes: 36,
  },
  {
    id: 3,
    title: 'UI设计语言与组件库',
    excerpt: '本文探讨现代UI设计语言和组件库的重要性，以及如何选择适合项目的UI库。',
    date: '2023-07-18',
    tags: ['UI', '组件库', '设计系统'],
    views: 1100,
    likes: 39,
  },
  {
    id: 4,
    title: 'JavaScript异步编程：从回调到Async/Await',
    excerpt:
      '本文将介绍JavaScript中异步编程的演变历程，从最初的回调函数，到Promise，再到现代的Async/Await语法。',
    date: '2023-07-10',
    tags: ['JavaScript', '异步编程', 'Async/Await'],
    views: 1500,
    likes: 58,
  },
  {
    id: 5,
    title: 'React Hooks深入理解与实践',
    excerpt:
      'React Hooks是React 16.8引入的新特性，它让你在不编写class的情况下使用state和其他React特性。本文将深入探讨Hooks的工作原理和最佳实践。',
    date: '2023-07-05',
    tags: ['React', 'Hooks', '函数组件'],
    views: 1800,
    likes: 76,
  },
  {
    id: 6,
    title: 'TypeScript入门指南：为JavaScript开发者准备',
    excerpt:
      'TypeScript是JavaScript的超集，它添加了静态类型检查和其他特性。本文将帮助JavaScript开发者快速入门TypeScript。',
    date: '2023-06-28',
    tags: ['TypeScript', 'JavaScript', '类型系统'],
    views: 1350,
    likes: 47,
  },
  {
    id: 7,
    title: '现代前端工程化实践',
    excerpt:
      '前端工程化是指将前端开发流程规范化、标准化，本文将介绍现代前端工程化的实践方法，包括构建工具、代码规范、自动化测试等。',
    date: '2023-06-20',
    tags: ['前端工程化', 'Webpack', 'CI/CD'],
    views: 1050,
    likes: 38,
  },
  {
    id: 8,
    title: 'CSS Grid布局完全指南',
    excerpt: 'CSS Grid是一种强大的二维布局系统，本文将全面介绍CSS Grid的使用方法和实践技巧。',
    date: '2023-06-15',
    tags: ['CSS', 'Grid', '响应式设计'],
    views: 950,
    likes: 32,
  },
];

// 模拟用户数据
const mockUserProfile: UserProfile = {
  name: '张三',
  title: '高级前端开发工程师',
  bio: '热爱Web开发和用户体验设计的前端工程师，专注于React生态系统和现代JavaScript应用程序开发。喜欢探索新技术并分享知识。',
  email: 'example@example.com',
  github: 'https://github.com/example',
  linkedin: 'https://linkedin.com/in/example',
  twitter: 'https://twitter.com/example',
};

const mockSkills: Skill[] = [
  { name: 'JavaScript', level: 95 },
  { name: 'React', level: 90 },
  { name: 'TypeScript', level: 85 },
  { name: 'HTML/CSS', level: 90 },
  { name: 'Node.js', level: 80 },
  { name: 'UMI', level: 85 },
  { name: 'Tailwind CSS', level: 88 },
  { name: 'Framer Motion', level: 75 },
];

const mockWorkExperience: WorkExperience[] = [
  {
    company: 'ABC科技有限公司',
    position: '高级前端开发工程师',
    period: '2021年1月 - 至今',
    description: '负责公司核心产品的前端架构设计和开发，优化用户体验和性能，指导初级开发人员。',
    technologies: ['React', 'TypeScript', 'UMI', 'Tailwind CSS'],
  },
  {
    company: 'XYZ互联网公司',
    position: '前端开发工程师',
    period: '2018年6月 - 2020年12月',
    description: '参与多个Web应用项目的开发，实现响应式设计和交互功能，解决浏览器兼容性问题。',
    technologies: ['JavaScript', 'Vue.js', 'SCSS', 'Webpack'],
  },
  {
    company: '创新科技初创公司',
    position: '初级前端开发人员',
    period: '2017年3月 - 2018年5月',
    description: '协助开发公司官网和内部管理系统，学习并应用前端最佳实践。',
    technologies: ['HTML', 'CSS', 'jQuery', 'Bootstrap'],
  },
];

// 模拟 API 类
export class MockApiService {
  // 文章相关
  static async getPosts(params?: any) {
    await delay(500); // 模拟网络延迟

    let filteredPosts = [...mockPosts];

    // 搜索过滤
    if (params?.search) {
      const searchLower = params.search.toLowerCase();
      filteredPosts = filteredPosts.filter(
        (post) =>
          post.title.toLowerCase().includes(searchLower) ||
          post.excerpt.toLowerCase().includes(searchLower),
      );
    }

    // 标签过滤
    if (params?.tag) {
      filteredPosts = filteredPosts.filter((post) => post.tags.includes(params.tag));
    }

    // 排序
    if (params?.sortBy) {
      filteredPosts.sort((a, b) => {
        let aValue = a[params.sortBy as keyof BlogPost];
        let bValue = b[params.sortBy as keyof BlogPost];

        if (params.sortBy === 'date') {
          aValue = new Date(a.date).getTime();
          bValue = new Date(b.date).getTime();
        }

        const result = aValue > bValue ? 1 : -1;
        return params.order === 'desc' ? -result : result;
      });
    }

    // 分页
    const page = params?.page || 1;
    const pageSize = params?.pageSize || 10;
    const start = (page - 1) * pageSize;
    const end = start + pageSize;

    const paginatedPosts = filteredPosts.slice(start, end);

    return {
      posts: paginatedPosts,
      total: filteredPosts.length,
      page,
      pageSize,
      totalPages: Math.ceil(filteredPosts.length / pageSize),
    };
  }

  static async getPost(id: string | number) {
    await delay(300);
    const post = mockPosts.find((p) => p.id === Number(id));
    if (!post) {
      throw new Error('Post not found');
    }
    return post;
  }

  static async getFeaturedPosts() {
    await delay(300);
    return mockPosts.slice(0, 3);
  }

  static async incrementViews(id: string | number) {
    await delay(200);
    const post = mockPosts.find((p) => p.id === Number(id));
    if (post) {
      post.views++;
      return { views: post.views };
    }
    throw new Error('Post not found');
  }

  static async likePost(id: string | number) {
    await delay(200);
    const post = mockPosts.find((p) => p.id === Number(id));
    if (post) {
      post.likes++;
      return { likes: post.likes };
    }
    throw new Error('Post not found');
  }

  // 标签相关
  static async getTags() {
    await delay(200);
    const allTags = [...new Set(mockPosts.flatMap((post) => post.tags))];
    return allTags;
  }

  static async getTagStats() {
    await delay(300);
    const tagCount: Record<string, number> = {};
    mockPosts.forEach((post) => {
      post.tags.forEach((tag) => {
        tagCount[tag] = (tagCount[tag] || 0) + 1;
      });
    });

    return Object.entries(tagCount).map(([tag, count]) => ({ tag, count }));
  }

  // 用户相关
  static async getUserProfile() {
    await delay(300);
    return mockUserProfile;
  }

  static async getUserSkills() {
    await delay(200);
    return mockSkills;
  }

  static async getUserWorkExperience() {
    await delay(200);
    return mockWorkExperience;
  }

  // 统计相关
  static async getSiteStats() {
    await delay(400);
    return {
      totalPosts: mockPosts.length,
      totalViews: mockPosts.reduce((sum, post) => sum + post.views, 0),
      totalLikes: mockPosts.reduce((sum, post) => sum + post.likes, 0),
      totalTags: [...new Set(mockPosts.flatMap((post) => post.tags))].length,
    };
  }
}

export default MockApiService;
